<template>
  <div class="app-echart">
    <!-- 无数据 -->
    <div v-if="nameData == 0">
      <el-empty :image-size="100" description="暂无数据"></el-empty>
    </div>
    <!-- 柱状图 -->
    <div id="echart" class="chartArea"></div>
  </div>
</template>

<script>
export default {
  name: "defectEchart",
  props: {
    echartDataFather: Object,
  },
  data() {
    return {
      openEmpty: true,
      // echart柱状图参数
      nameData: [], //横坐标名称
      categoryCounts: [], //柱状图数据
      // echart实例
      myChart: null,
    };
  },
  methods: {
    // 加载echart
    getLoadEcharts() {
      this.myChart = this.$echarts.init(document.getElementById("echart"));
      var option = {
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "shadow",
          },
          backgroundColor: "#fff", // 悬浮框背景色
          borderColor: "#000", // 悬浮框边框颜色
          borderWidth: 1, // 悬浮框边框宽度
          textStyle: {
            // 悬浮框文字样式
            color: "#000",
            fontSize: 12,
          },
        },
        grid: {
          top: "8%",
          left: "3%", //默认10%
          right: "3%", //默认10%
          bottom: "3%", //默认60
          containLabel: true,
          //grid区域是否包含坐标轴的刻度标签
          // width: "100%", // 设置图表宽度为父容器的80%
          // height: "100%", // 设置图表高度为父容器的80%
        },
        xAxis: {
          type: "category",
          data: this.nameData,
          axisLabel: {
            interval: 0,
            rotate: 30,
            margin: 10,
          },
        },
        yAxis: {
          type: "value",
        },
        series: [
          {
            data: this.categoryCounts,
            type: "bar",
            showBackground: true,
            backgroundStyle: {
              color: "rgba(180, 180, 180, 0.2)",
            },
          },
        ],
      };
      this.myChart.setOption(option);
    },
  },
  watch: {
    echartDataFather: {
      handler(newValue) {
        // 没有数据释放实例
        if (newValue.categoryCounts.length == 0) {
          this.nameData = [];
          this.categoryCounts = [];
          this.myChart.dispose();
          this.myChart = null;
          return;
        }
        // 挂载更新实例
        (this.nameData = newValue.nameData),
          (this.categoryCounts = newValue.categoryCounts);
        this.getLoadEcharts();
      },
      // deep: true
    },
  },
};
</script>

<style lang="scss" scoped>
.app-echart {
  background-color: #ffffff;
  height: 100%;
  width: 100%;
  display: block;
}
.chartArea {
  align-items: center;
  justify-content: center;
  // margin-left: 10px;
  height: 100%;
  width: 100%;
}
</style>
